//
//  BJEditViewController.m
//  BowJoy
//
//  Created by  on 2024/5/14.
//

#import "BJEditViewController.h"
#import "ShowTimeStyle.h"
#import "XWCountryCodeController.h"
#import <Photos/Photos.h>
#import "BJPickerView.h"

@interface BJEditViewController ()<DatePickerViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIView *bgGroundView;
@property (weak, nonatomic) IBOutlet UIImageView *headerIcon;
@property (weak, nonatomic) IBOutlet UIImageView *editIcon;

@property (weak, nonatomic) IBOutlet UITextField *nikeNameTextFiled;

@property (weak, nonatomic) IBOutlet UILabel *dateBirthL;

@property (weak, nonatomic) IBOutlet UILabel *countryL;

@property (nonatomic)BOOL hasChangeheader;
@property (weak, nonatomic) IBOutlet UIImageView *headerFramImae;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pictureRightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pictureBottomConstraint;

@property (nonatomic,strong) BJPickerView *datePickerView;
@end




@implementation BJEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.naviTitle = @"Edit Profile";
    [self bindingEvent];
    [self.headerIcon setImageURL:[NSURL URLWithString:[BJUserManager sharedManager].userInfoData.avatarUrl]];
    self.nikeNameTextFiled.text = [BJUserManager sharedManager].userInfoData.nickname;
    
    self.dateBirthL.text = [BJUserManager sharedManager].userInfoData.birthday;
    self.countryL.text = [BJUserManager sharedManager].userInfoData.country;
    NSString *iconPictureFrame =  [[NSUserDefaults standardUserDefaults] objectForKey:KSelectPictureFrameKey];
    if (iconPictureFrame) {
        self.headerFramImae.image = [UIImage imageNamed:iconPictureFrame];
        self.pictureRightConstraint.constant = 10;
        self.pictureBottomConstraint.constant = 10;

    }else{
        self.pictureRightConstraint.constant = 30;
        self.pictureBottomConstraint.constant = 30;

    }
    // Do any additional setup after loading the view from its nib.
}


//事件绑定
-(void)bindingEvent{
    
    kWeakSelf(weakSelf)
    self.headerIcon.onClick(^{
        [weakSelf presstap];
    });
    self.editIcon.onClick(^{
        [weakSelf presstap];
    });
    
}

- (void)presstap {
    UIAlertController* alertion = [UIAlertController alertControllerWithTitle:@"please" message:@"select" preferredStyle:UIAlertControllerStyleActionSheet] ;
    UIAlertAction* camera = [UIAlertAction actionWithTitle:@"camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        // 检查相机权限
        AVAuthorizationStatus cameraAuthorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (cameraAuthorizationStatus == AVAuthorizationStatusRestricted ||
            cameraAuthorizationStatus == AVAuthorizationStatusDenied) {
            // 用户已拒绝访问，或者访问受限（例如家长控制）
            // 处理未授权的情况
            [ASHUD showWithText:@"You have not authorised this permission." afterDelay:1];

        } else if (cameraAuthorizationStatus == AVAuthorizationStatusNotDetermined) {
            // 用户尚未选择，请求权限
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    // 用户已授权访问相机
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // 在这里执行你的UI更新操作
                        // 这些操作将在主线程中执行
                        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                        picker.delegate = self;
                        picker.sourceType = UIImagePickerControllerSourceTypeCamera; // 图片来源于相册
                        [self presentViewController:picker animated:YES completion:nil];
                    });
                } else {
                    // 用户拒绝访问相机
                }
            }];
        } else {
            // 用户已授权访问相机
            dispatch_async(dispatch_get_main_queue(), ^{
                // 在这里执行你的UI更新操作
                // 这些操作将在主线程中执行
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.delegate = self;
                picker.sourceType = UIImagePickerControllerSourceTypeCamera; // 图片来源于相册
                [self presentViewController:picker animated:YES completion:nil];
            });
        }
        

    }] ;
    UIAlertAction* photo = [UIAlertAction actionWithTitle:@"photo" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 检查相册权限
        PHAuthorizationStatus photoAuthorizationStatus = [PHPhotoLibrary authorizationStatus];
        if (photoAuthorizationStatus == PHAuthorizationStatusRestricted ||
            photoAuthorizationStatus == PHAuthorizationStatusDenied) {
            // 用户已拒绝访问，或者访问受限
            // 处理未授权的情况
            [ASHUD showWithText:@"You have not authorised this permission." afterDelay:1];
        } else if (photoAuthorizationStatus == PHAuthorizationStatusNotDetermined) {
            // 用户尚未选择，请求权限
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if (status == PHAuthorizationStatusAuthorized) {
                    // 用户已授权访问相册
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // 在这里执行你的UI更新操作
                        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                        picker.delegate = self;
                        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; // 图片来源于相册
                        [self presentViewController:picker animated:YES completion:nil];
                    });
                } else {
                    // 用户拒绝访问相册
//                    [ASHUD showWithText:@"You have not authorised this permission." afterDelay:1];
                }
            }];
        } else {
            // 用户已授权访问相册
            dispatch_async(dispatch_get_main_queue(), ^{
                // 在这里执行你的UI更新操作
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.delegate = self;
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; // 图片来源于相册
                [self presentViewController:picker animated:YES completion:nil];
            });
        }
        

    }] ;
    UIAlertAction* cancal = [UIAlertAction actionWithTitle:@"cancal" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }] ;
    [alertion addAction:camera] ;
    [alertion addAction:photo] ;
    [alertion addAction:cancal] ;
    
    [self presentViewController:alertion animated:YES completion:nil] ;
    
}


#pragma mark - UIImagePickerControllerDelegate
 
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    // 处理选中的图片
    
    UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
    CGSize size = CGSizeMake(0.01, 0.01);
    UIImage *newheaderimg = [self compressOriginalImage:image toSize:size];
    [self.headerIcon setImage:newheaderimg];
    self.hasChangeheader = YES;
 
    [picker dismissViewControllerAnimated:YES completion:nil];
}
 
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//压缩图片
-(UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{
    UIImage * resultImage = image;
    UIGraphicsBeginImageContext(size);
    [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIGraphicsEndImageContext();
    return image;
}

- (IBAction)clickDateOfBirthBtn:(id)sender {
    [self.view endEditing:YES];
    
    BJPickerView* datePickerView = [[BJPickerView alloc] init];
    datePickerView.delegate = self;
    [datePickerView setDefaultTSelectYear:self.dateBirthL.text];
    self.datePickerView = datePickerView;
    [datePickerView show];

}
// 处理选择的日期
- (void)pickerDateView:(BasePickerView *)pickerDateView selectYear:(NSInteger)year selectMonth:(NSInteger)month selectDay:(NSInteger)day {
    NSString *monthStr = [NSString stringWithFormat:@"%ld",(long)month];
    NSString *dayStr = [NSString stringWithFormat:@"%ld",(long)day];

    if (month<10) {
        monthStr = [NSString stringWithFormat:@"0%ld",(long)month];
    }
    if (day<10) {
        dayStr = [NSString stringWithFormat:@"0%ld",(long)day];
    }
    
    NSString* string = [NSString stringWithFormat:@"%ld-%@-%@", year, monthStr, dayStr];
    NSLog(@"%@",string);
    self.dateBirthL.text = string;
}

- (IBAction)clickCountryBtn:(id)sender {
    XWCountryCodeController *CountryCodeVC = [[XWCountryCodeController alloc] init];
    //使用block回调
    kWeakSelf(weakSelf)
    [CountryCodeVC setReturnCountryCodeBlock:^(NSString *countryName, NSString *code) {
        [weakSelf.countryL setText:countryName];
    }];
    [self.navigationController pushViewController:CountryCodeVC animated:YES];
}


- (IBAction)clickSubmitBtn:(id)sender {
    
    if(self.hasChangeheader == NO){
        [self saveOtherInfo];
    }else{
        //保存头像
        [ASHUD showASLoading];
        [[BJNetManager shareNetManager] postUploadImageToOssWithImage:self.headerIcon.image completionHandler:^(id  _Nonnull responOj, NSError * _Nonnull error) {
            NSDictionary *dict = responOj;
            NSInteger code = [dict[@"code"] integerValue];
            if(!error && code == 0){
                NSDictionary *data = dict[@"data"];
                NSString *filename = data[@"filename"];
                NSLog(@"filename_%@",filename);
                [[BJNetManager shareNetManager] postUpdateAvatarWithAvatarPath:filename completionHandler:^(id  _Nonnull responOj, NSError * _Nonnull error) {
                    [ASHUD hideHUD];
                    if(!error){
                        [self saveOtherInfo];
                    }
                }];
            }else{
                [ASHUD showWithText:@"error" afterDelay:1];
            }
        }];
    }

    
}

//保存除图片外的其他信息
- (void)saveOtherInfo{

    //保存其他
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.nikeNameTextFiled.text ? self.nikeNameTextFiled.text : @""  forKey:@"nickname"];
    [param setObject:self.dateBirthL.text ? self.dateBirthL.text : @"" forKey:@"birthday"];
    [param setObject:self.countryL.text ? self.countryL.text : @"" forKey:@"country"];
    [ASHUD showASLoading];
    [[BJNetManager shareNetManager]postSaveUserInfoWithParam:param completionHandler:^(id  _Nonnull responOj, NSError * _Nonnull error) {
        [ASHUD hideHUD];
        if(!error){
            NSDictionary *dict = [NSDictionary modelWithJSON:responOj];
            
            NSInteger code = [dict[@"code"] integerValue];
            if(code == 0){
                if(self.updateUserInfo){
                    self.updateUserInfo();
                }
                [self.navigationController popViewControllerAnimated:YES];
                [ASHUD showWithText:@"Edit successfully" afterDelay:2];
            }else{
                NSString *msg = dict[@"msg"];
                [ASHUD showWithText:msg afterDelay:1];
            }
            
        }else{
            [ASHUD showWithText:@"error" afterDelay:1];
        }
    }];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
